﻿using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using iWare.Wms.WorkerService.ThirdDB;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class OrderERP : BackgroundService
    {
        private readonly ILogger<OrderERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public OrderERP(ILogger<OrderERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时同步调拨单信息
                await Order();

                await Task.Delay(10 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时同步调拨单信息
        /// <summary>
        /// 定时同步调拨单信息
        /// </summary>
        /// <returns></returns>
        public async Task Order()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _wareOrderRep = Db.GetRepository<WareOrder>(services);
                var _wareOrderDetailsRep = Db.GetRepository<WareOrderDetails>(services);

                var invtaOutputList = await respository
                .SqlQueryAsync<INVTAOutput>
                (@"select TA033,  --项目编号
	                      TA001,  --单别(1201、1202、1203、1204（12开头)
	                      TA002,  --单号
	                      TA003,  --交易日期（[FORMATE:YMD]）
						  TA004,  --部门编号
						  TA005,  --备注
                          TA006,  --审核码（Y/N/V）
						  TA008,  --工厂编号
	                      TA009,  --单据性质码（11.一般单据、12.调拨单）
	                      TA011,  --总数量
	                      TA014,  --单据日期
	                      TA015,  --审核者
	                      UDF01,  --（工位编号）用户自定义字段1
	                      UDF02,  --（主件品号）用户自定义字段1
	                      UDF08   --（设备编号）用户自定义字段1
                   from INVTA where TA001 like '12%' and TA006='Y' and TA002!='20171219001' and TA009=12 and DATEDIFF(dd,TA014,GETDATE())<=3 order by TA014 desc");

                //循环判断LES系统中是否包含该调拨信息
                List<WareOrder> orderList = new List<WareOrder>();
                foreach (var invta in invtaOutputList)
                {
                    var wareOrder = await _wareOrderRep.FirstOrDefaultAsync(u => u.OrderCategory == invta.TA001.Trim() && u.OrderNo == invta.TA002.Trim()
                    && u.ProjectCode == invta.TA033.Trim() && u.OrderQuantityTotal == invta.TA011);

                    //不存在执行新增操作
                    if (wareOrder == null)
                    {
                        var addOrder = new WareOrder()
                        {
                            Id = YitIdHelper.NextId(),
                            OrderNo = invta.TA002?.Trim(),
                            OrderCategory = invta.TA001?.Trim(),
                            OrderType = IssueTypeEnum.DIAOBO,
                            ProjectCode = invta.TA033?.Trim(),
                            OrderQuantityTotal = invta.TA011,
                            DepartmentNumber = invta.TA004?.Trim(),
                            OrderRemark = invta.TA005?.Trim(),
                            AuditCode = invta.TA006?.Trim(),
                            FactoryCode = invta.TA008?.Trim(),
                            OrderDate = invta.TA014?.Trim(),
                            StationNumber = invta.UDF01?.Trim(),
                            MainPartNumber = invta.UDF02?.Trim(),
                            EquipmentNumber = invta.UDF08?.Trim(),
                            CreatedUserName = "LES SYSTEM".Trim(),
                            CreatedTime = DateTimeOffset.Now
                        };

                        // 新增单据主表信息
                        await _wareOrderRep.InsertNowAsync(addOrder);

                        // 批量新增单据明细信息
                        var orderDetailsList = await Orderdetails(addOrder);
                        if (orderDetailsList.Count != 0) await _wareOrderDetailsRep.InsertNowAsync(orderDetailsList);
                    }
                    else
                    {
                        // 批量新增单据明细信息
                        var orderDetailsList = await Orderdetails(wareOrder);
                        if (orderDetailsList.Count != 0) await _wareOrderDetailsRep.InsertNowAsync(orderDetailsList);
                    }
                }
            }
            Console.WriteLine("定时同步调拨单信息");
        }
        #endregion

        #region 调拨单身-Les单据明细表
        /// <summary>
        /// 调拨单身-Les单据明细表
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<List<WareOrderDetails>> Orderdetails(WareOrder order)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _wareOrderRep = Db.GetRepository<WareOrder>(services);
                var _wareOrderDetailsRep = Db.GetRepository<WareOrderDetails>(services);
                var _wareMaterialRep = Db.GetRepository<WareMaterial>(services);

                if (string.IsNullOrEmpty(order.OrderNo)) throw Oops.Oh(ErrorCode.D1011);
                var invtbOutputList = await respository
                .SqlQueryAsync<INVTBOutput>
                (@"select  TB012,   --转出库
		                   TB013,   --转入库
		                   TB021,   --项目编号
		                   TB029,   --转出库位
		                   TB030,   --转入库位
		                   TB001,   --单别
		                   TB002,   --单号
		                   TB003,   --序号
		                   TB004,   --品号
		                   TB005,   --品名
		                   TB006,   --规格
		                   TB007,   --数量
		                   TB008,   --单位
		                   TB009,   --库存数量
						   TB018,   --审核码
						   CREATOR, --审核者
                           TB017,   --备注
                           UDF02    --参数
                   from INVTB where TB018='Y' and TB001='" + order.OrderCategory + "' and  TB002='" + order.OrderNo + "' and TB021='" + order.ProjectCode + "' order by CREATE_DATE desc");

                //循环判断LES系统中是否包含该调拨明细信息
                List<WareOrderDetails> orderDetailsList = new List<WareOrderDetails>();
                foreach (var invtb in invtbOutputList)
                {
                    var isExists = await _wareOrderDetailsRep.AnyAsync(u => u.WareOrder.OrderCategory == invtb.TB001.Trim() && u.WareOrder.OrderNo == invtb.TB002.Trim()
                    && u.ProjectCode == invtb.TB021.Trim() && u.Code == invtb.TB004.Trim() && u.SpecificationModel == invtb.TB006.Trim());

                    //不存在执行新增操作
                    if (!isExists)
                    {
                        //获取物料的检验方式
                        var InspectionMethod = InspectionMethodEnum.mianjian;
                        var wareMateriaModel = await _wareMaterialRep.FirstOrDefaultAsync(n => n.Code == invtb.TB004.Trim()
                        && n.Name == invtb.TB005.Trim() && n.SpecificationModel == invtb.TB006.Trim());
                        if (wareMateriaModel != null) InspectionMethod = wareMateriaModel.InspectionMethod;

                        // 品牌名称查询
                        var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == invtb.TB004.Trim()
                        && z.Name == invtb.TB005.Trim() && z.SpecificationModel == invtb.TB006.Trim());

                        var addOrderDetails = new WareOrderDetails()
                        {
                            Id = YitIdHelper.NextId(),
                            OrderId = order.Id,
                            ProjectCode = invtb.TB021?.Trim(),
                            XuHao = invtb.TB003?.Trim(),
                            Code = invtb.TB004?.Trim(),
                            Name = invtb.TB005?.Trim(),
                            SpecificationModel = invtb.TB006?.Trim(),
                            Unit = invtb.TB008?.Trim(),
                            BrandName = wareMaterial == null || wareMaterial.BrandName == "无" ? "" : wareMaterial.BrandName,
                            InspectionMethod = InspectionMethod,
                            OrderQuantity = invtb.TB007,
                            ActualQuantity = new decimal(0.00),
                            SingleCategory = invtb.TB001?.Trim(), //单别
                            TransferToIssue = invtb.TB012?.Trim(), //转出库
                            TransferToReceipt = invtb.TB013?.Trim(), //转入库
                            TransferOutLocation = invtb.TB029?.Trim(), //转出库位
                            TransferredILocation = invtb.TB030?.Trim(), //转入库位
                            OrderParameter = invtb.UDF02?.Trim(), //参数
                            OrderRemark = invtb.TB017?.Trim(), //备注
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        orderDetailsList.Add(addOrderDetails);
                    }
                }

                return orderDetailsList;
            }
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
